package day09;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//模拟题1-三数之和-复习题
public class 三数之和 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        int n = nums.length;
        // 排序
        Arrays.sort(nums);
        for(int i = 0;i < n;){  if(nums[i] > 0){
                break;
            }
            int left = i + 1,right = n - 1,tmp = -nums[i];
            while(left < right){
                if(nums[left] + nums[right] > tmp){
                    right--;
                }else if(nums[left] + nums[right] < tmp){
                    left++;
                }else{
                    List<Integer> list = Arrays.asList(nums[i],nums[left],nums[right]);
                    ret.add(list);
                    left++;
                    right--;
                    //去重
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                }
            }
            //去重 i
            i++;
            while(i < n && nums[i] == nums[i - 1]){
                i++;
            }
        }
        return ret;
    }
    /*public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            //去重
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1, right = n - 1;
            int tmp = -nums[i];
            while (left < right) {
                if (nums[left] + nums[right] > tmp) {
                    right--;
                } else if (nums[left] + nums[right] < tmp) {
                    left++;
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    ret.add(list);
                    //进行去重
                    while(left < right && nums[left] == nums[left + 1]){
                        left++;
                    }
                    while(left < right && nums[right] == nums[right - 1]){
                        right--;
                    }
                    //指针同时移动
                    left++;
                    right--;
                }
            }
        }
        return ret;
    }*/
}
